<template>
  <div class="emergency-summary-node">
    <div class="node-header">
      <h3 class="node-title">应急总结</h3>
      <div class="header-buttons">
        <el-tag type="info" v-if="reportList.length > 0">{{ reportInfoText }}</el-tag>
        <el-button type="success" @click="handleSave" v-if="!isCompleted">保存报告</el-button>
        <el-button type="primary" @click="handleComplete" v-if="!isCompleted">完成总结</el-button>
        <el-button v-if="reportList.length > 1" @click="loadNextReport">查看下一条</el-button>
      </div>
    </div>

    <!-- 事件详情 -->
    <div class="event-details-section">
      <div class="section-title">事件详情</div>
      <el-descriptions border :column="2">
        <el-descriptions-item label="事件编号">{{ eventData.id }}</el-descriptions-item>
        <el-descriptions-item label="发生地点">{{ eventData.location }}</el-descriptions-item>
        <el-descriptions-item label="发生时间">{{ eventData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="事件描述" :span="2">{{ eventData.description }}</el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 应急总结表单 -->
    <div class="summary-form-section">
      <div class="section-title">应急总结报告</div>
      <el-form ref="summaryFormRef" :model="summaryForm" :rules="summaryRules" label-width="120px" :disabled="isCompleted || flowStatus === 7">
        <el-form-item label="工作类型" prop="workType">
          <el-select v-model="summaryForm.workType" disabled class="w-full">
            <el-option value="应急处置" label="应急处置" />
          </el-select>
        </el-form-item>
        <el-form-item label="总结时间" prop="summaryTime">
          <el-date-picker 
            v-model="summaryForm.summaryTime" 
            type="datetime" 
            placeholder="选择总结时间"
            value-format="YYYY-MM-DD HH:mm:ss" 
            class="w-full" 
          />
        </el-form-item>
        <el-form-item label="负责人" prop="responsible">
          <el-input v-model="summaryForm.responsible" placeholder="请输入负责人姓名" :disabled="flowStatus === 7" />
        </el-form-item>
        <el-form-item label="工作内容" prop="workContent">
          <el-input 
            type="textarea" 
            v-model="summaryForm.workContent" 
            :rows="3" 
            placeholder="请详细描述工作内容" 
            :disabled="flowStatus === 7"
          />
        </el-form-item>
        <el-form-item label="主要成果" prop="mainAchievements">
          <el-input 
            type="textarea" 
            v-model="summaryForm.mainAchievements" 
            :rows="3" 
            placeholder="请描述工作取得的主要成果" 
            :disabled="flowStatus === 7"
          />
        </el-form-item>
        <el-form-item label="存在问题" prop="existingProblems">
          <el-input 
            type="textarea" 
            v-model="summaryForm.existingProblems" 
            :rows="3" 
            placeholder="请描述工作中存在的问题" 
            :disabled="flowStatus === 7"
          />
        </el-form-item>
        <el-form-item label="改进建议" prop="improvements">
          <el-input 
            type="textarea" 
            v-model="summaryForm.improvements" 
            :rows="3" 
            placeholder="请提出改进建议" 
            :disabled="flowStatus === 7"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input 
            type="textarea" 
            v-model="summaryForm.remarks" 
            :rows="2" 
            placeholder="请输入备注信息" 
            :disabled="flowStatus === 7"
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 提示信息 -->
    <div class="tip-section">
      <el-alert
        v-if="!isCompleted"
        title="请保存总结报告后，点击'完成总结'按钮结束整个应急处置流程"
        type="success"
        :closable="false"
        show-icon
      />
      <el-alert
        v-else
        title="该事件已完成处理，总结报告不可编辑"
        type="info"
        :closable="false"
        show-icon
      />
    </div>

    <!-- 完成确认对话框 -->
    <el-dialog v-model="confirmDialogVisible" title="完成总结" width="400px">
      <div class="confirm-content">
        <el-icon :size="48" color="#67C23A"><CircleCheck /></el-icon>
        <p class="confirm-message">确定要完成应急总结吗？</p>
        <p class="confirm-desc">完成后将关闭该事件，无法再进行修改</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="confirmDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmComplete">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 保存成功提示 -->
    <el-dialog v-model="saveSuccessVisible" title="保存成功" width="400px">
      <div class="confirm-content">
        <el-icon :size="48" color="#67C23A"><CircleCheck /></el-icon>
        <p class="confirm-message">应急总结报告已保存成功</p>
        <p class="confirm-desc">您可以继续编辑或点击"完成总结"按钮关闭事件</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveSuccessVisible = false">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { updateEmergencyEvent } from '@/api/bridge/command/event';
import { getWorkSummary, addWorkSummary, updateEWorkSummary } from '@/api/bridge/command/work';
import dayjs from 'dayjs';
import { CircleCheck } from '@element-plus/icons-vue';

const props = defineProps({
  eventData: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['complete-summary']);

// 判断是否已完成（不允许编辑）
const isCompleted = computed(() => {
  return props.eventData && props.eventData.flowStatus === 7;
});

const flowStatus = computed(() => props.eventData.flowStatus);

// 报告列表
const reportList = ref<any[]>([]);
const currentReportIndex = ref(0);

// 显示报告信息
const reportInfoText = computed(() => {
  if (reportList.value.length > 0) {
    return `共 ${reportList.value.length} 条报告，当前第 ${currentReportIndex.value + 1} 条`;
  }
  return '暂无报告';
});

// 总结表单
const summaryFormRef = ref();
const summaryForm = ref({
  id: "",
  workType: "应急处置",
  summaryTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
  responsible: "",
  workContent: "",
  mainAchievements: "",
  existingProblems: "",
  improvements: "",
  status: 1,
  remarks: "",
  eventId: ""
});

// 表单校验规则
const summaryRules = {
  summaryTime: [
    { required: true, message: "请选择总结时间", trigger: "change" }
  ],
  responsible: [
    { required: true, message: "请输入负责人姓名", trigger: "blur" }
  ],
  workContent: [
    { required: true, message: "请输入工作内容", trigger: "blur" }
  ],
  mainAchievements: [
    { required: true, message: "请输入主要成果", trigger: "blur" }
  ]
};

// 对话框控制
const confirmDialogVisible = ref(false);
const saveSuccessVisible = ref(false);

// 加载下一条报告
const loadNextReport = () => {
  if (reportList.value.length <= 1) return;
  
  currentReportIndex.value = (currentReportIndex.value + 1) % reportList.value.length;
  const nextReport = reportList.value[currentReportIndex.value];
  summaryForm.value = { ...nextReport };
};

// 获取报告列表
const fetchReportList = async () => {
  try {
    if (!props.eventData || !props.eventData.id) return;
    
    const params = {
      eventId: props.eventData.id,
      pageNum: 1,
      pageSize: 10
    };
    
    const res = await getWorkSummary(params);
    if (res.code === 200) {
      reportList.value = res.rows || [];
      
      // 如果有报告，显示第一条
      if (reportList.value.length > 0) {
        currentReportIndex.value = 0;
        summaryForm.value = { ...reportList.value[0] };
      }
    }
  } catch (error) {
    console.error('获取报告列表失败:', error);
  }
};

// 保存报告
const handleSave = async () => {
  if (!summaryFormRef.value) return;
  
  await summaryFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 设置事件ID
        summaryForm.value.eventId = props.eventData.id;
        
        // 根据是否有ID决定是新增还是更新
        const hasId = !!summaryForm.value.id;
        const actionApi = hasId ? updateEWorkSummary : addWorkSummary;
        const res = await actionApi(summaryForm.value);
        
        if (res.code === 200) {
          ElMessage.success(hasId ? '报告更新成功' : '报告保存成功');
          saveSuccessVisible.value = true;
          
          // 如果是新增，设置返回的ID
          if (!hasId && res.data) {
            summaryForm.value.id = res.data.id;
          }
          
          // 重新获取报告列表
          await fetchReportList();
        } else {
          ElMessage.error(res.msg || '保存失败');
        }
      } catch (error) {
        console.error('保存报告失败:', error);
        ElMessage.error('保存失败');
      }
    } else {
      ElMessage.warning('请完善表单信息');
    }
  });
};

// 完成总结
const handleComplete = async () => {
  if (!summaryFormRef.value) return;
  
  await summaryFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      confirmDialogVisible.value = true;
    } else {
      ElMessage.warning('请完善表单信息');
    }
  });
};

// 确认完成总结
const confirmComplete = async () => {
  try {
    // 不直接调用API更新事件状态，避免与父组件的状态更新重复
    // 只触发事件，由父组件统一处理状态更新
    ElMessage.success('总结已完成，事件已关闭');
    confirmDialogVisible.value = false;
    emit('complete-summary');
  } catch (error) {
    console.error('完成总结失败:', error);
    ElMessage.error('操作失败');
  }
};

// 获取事件类型名称
const getEventTypeName = (type: number) => {
  const types = {
    1: '自然灾害',
    2: '事故灾难',
    3: '公共卫生',
    4: '社会安全'
  };
  return types[type] || '-';
};

// 获取事件类型标签样式
const getEventTypeTag = (type: number) => {
  const tags = {
    1: 'danger',
    2: 'warning',
    3: 'success',
    4: 'info'
  };
  return tags[type] || '';
};

// 获取优先级名称
const getPriorityName = (priority: number) => {
  const priorities = {
    1: '低',
    2: '中',
    3: '高',
    4: '紧急'
  };
  return priorities[priority] || '-';
};

// 获取优先级标签样式
const getPriorityTag = (priority: number) => {
  const tags = {
    1: 'info',
    2: 'warning',
    3: 'danger',
    4: 'danger'
  };
  return tags[priority] || '';
};

onMounted(() => {
  fetchReportList();
});
</script>

<style scoped lang="scss">
.emergency-summary-node {
  padding: 20px;
  
  .node-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .node-title {
      font-size: 18px;
      font-weight: 600;
      margin: 0;
      color: var(--el-text-color-primary);
    }
    
    .header-buttons {
      display: flex;
      gap: 12px;
      align-items: center;
    }
  }
  
  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 16px;
    color: var(--el-text-color-primary);
    display: flex;
    align-items: center;
    
    &::before {
      content: '';
      display: inline-block;
      width: 4px;
      height: 16px;
      background-color: var(--el-color-primary);
      margin-right: 8px;
      border-radius: 2px;
    }
  }
  
  .event-details-section,
  .summary-form-section {
    background-color: var(--el-bg-color-overlay);
    padding: 20px;
    border-radius: 4px;
    box-shadow: var(--el-box-shadow-light);
    margin-bottom: 24px;
  }
  
  .w-full {
    width: 100%;
  }
  
  .tip-section {
    margin-top: 20px;
  }
  
  .confirm-content {
    text-align: center;
    padding: 20px 0;
    
    .confirm-message {
      font-size: 16px;
      font-weight: 500;
      margin: 16px 0 8px;
      color: var(--el-text-color-primary);
    }
    
    .confirm-desc {
      color: var(--el-text-color-secondary);
      margin: 0;
    }
  }
}
</style> 